package com.wenbing.miio.core;

import com.wenbing.miio.core.exception.NetworkLayerException;
import com.wenbing.miio.util.function.Consumer;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * 出栈方向的回调适配
 * 将出栈数据封装为RowFrame转交Consumer处理
 * @author wen bing
 * @projectName: miio
 * @package: com.wenbing.miio.core
 * @className: BottomNetworkLayer
 * @date 2024/09/21 17:21
 **/
public class OutboundConsumerNetworkLayer extends AbstractNetworkLayer {

    private Consumer<RowFrame> rowFrameConsumer;

    public OutboundConsumerNetworkLayer(Consumer<RowFrame> rowFrameConsumer) {
        assert rowFrameConsumer != null;
        this.rowFrameConsumer = rowFrameConsumer;
    }

    public void setRowFrameConsumer(Consumer<RowFrame> rowFrameConsumer) {
        this.rowFrameConsumer = rowFrameConsumer;
    }

    @Override
    protected ByteBuffer unpacking(NetworkLayerContext context, ByteBuffer packingData) throws IOException, NetworkLayerException {
        return packingData;
    }

    @Override
    protected ByteBuffer packing(NetworkLayerContext context, ByteBuffer packingData) throws IOException, NetworkLayerException {
        return packingData;
    }

    @Override
    protected void deliverUpperLayer(NetworkLayerContext context, ByteBuffer packingData) throws NetworkLayerException, IOException {
        LOGGER.info("outbound send rowFrame to the rowFrameConsumer");
        rowFrameConsumer.accept(new RowFrame(context, packingData));
    }
}
